var net = require('net')
var fs = require('fs')

var plane = {
	ch:undefined,
	online:false
}

var gcs = {
	ch:undefined,
	online:false
}

var server = net.createServer(function(c){
	var count = 0

	c.on('data',function(data){
		count ++
		console.log(data)
		if(count == 1) {
			// 1.确认终端类型 0x01 飞机 0x02 地面站
			// 2.如果是地面站，如果当前有在线的飞机，返回1，没有飞机不在线就返回0||如果是飞机，如果有地面站在线，返回1，没有地面站在线就返回0

			if(data[0] == 0x01) {
				// 飞机连接
				c.clientType = "plane"
				plane.ch = c
				plane.online = true

				if(gcs.online && gcs.ch) {
					c.write("1")
					gcs.ch.write("200")
				}else {
					c.write("0")
				}
			} else if (data[0] == 0x02) {
				// 地面站连接
				c.clientType = "gcs"
				gcs.ch = c
				gcs.online = true

				if(plane.online && plane.ch) {
					c.write("1")
				}else {
					c.write("0")
				}
			} else {
				// fatal error
				c.write("500") 
				c.destroy(new Error('fatal error'))
			}

		} else {
			// 正常数据包透传
			if(c.clientType == "plane") {
				console.log('from plane:',data)
				if (gcs.online && gcs.ch) {
					console.log('to gcs:',data)
					gcs.ch.write(data)
				} else {
					console.log('gcs不在线')
					console.log(data)
					c.write("404")
				}
			} else if (c.clientType == "gcs") {
				console.log('from gcs:',data)
				if (plane.online && plane.ch) {
					console.log('to plane:',data)
					plane.ch.write(data)
				} else {
					console.log('plane不在线')
					console.log(data)
					c.write("404")
				}
			} else {
				// fatal error
				c.write("500") 
				c.destroy(new Error('fatal error'))
			}
		}
	})

	// 超过30s 未收到消息
	c.setTimeout(30000,function(){
		console.log('客户端在30s内未通信，将断开连接...')
	})

	c.on('timeout',function(){
		// c.end()
		c.destroy(new Error('timeout',c.clientType))
	})

	c.on('end',function(){
		console.log('断开连接')
		if (c.clientType == 'plane') {
			plane.ch = undefined
			plane.online = false
			if(gcs.online && gcs.ch){
				console.log('plane if off,notify gcs',new Date())
                gcs.ch.write("404")
            }
		} else if(c.clientType == 'gcs'){
			gcs.ch = undefined
			gcs.online = false
		} else {
			console.log('尚未确认终端类型')
		}
	})

	c.on('close',function(){
		console.log('断开连接')
		if (c.clientType == 'plane') {
			plane.ch = undefined
			plane.online = false
			if(gcs.online && gcs.ch){
				console.log('plane if off,notify gcs',new Date())
                gcs.ch.write("404")
            }
		} else if(c.clientType == 'gcs'){
			gcs.ch = undefined
			gcs.online = false
		} else {
			console.log('尚未确认终端类型')
		}
	})

	c.on('error',function(){
		console.log('断开连接')
		if (c.clientType == 'plane') {
			plane.ch = undefined
			plane.online = false
			if(gcs.online && gcs.ch){
				console.log('plane if off,notify gcs',new Date())
                gcs.ch.write("404")
            }
		} else if(c.clientType == 'gcs'){
			gcs.ch = undefined
			gcs.online = false
		} else {
			console.log('尚未确认终端类型')
		}
	})
})

server.on('error',function(err){
	console.log('fatal error',err)
	process.exit(1)
})

server.listen(3000)

